<script setup lang="ts">
import { onMounted, ref } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { request } from '@/utils/request'
import { useRoute } from 'vue-router'

const route = useRoute()

window._AMapSecurityConfig = {
  securityJsCode: '415e917da833efcf2d5b69f4d821784b'
}

// 进入页面获取物流信息
const item = ref<any>({})

onMounted(async () => {
  // 获取物流数据
  const res = await request<any>(
    `/patient/order/${route.query.orderId}/logistics`
  )
  item.value = res.data
  console.log(item.value)

  // 加载高德地图库
  const AMap = await AMapLoader.load({
    key: '4eed3d61125c8b9c168fc22414aaef7e',
    version: '2.0'
  })

  // 创建地图实例并使用
  const map = new AMap.Map('myMap', {
    zoom: 11, //级别
    center: [116.397428, 39.90923], //中心点坐标
    viewMode: '3D' //使用3D视图
  })

  AMap.plugin('AMap.Driving', function () {
    const driving = new AMap.Driving({
      map: map,
      showTraffic: false
    })

    // 起点
    const start = item.value.logisticsInfo.shift()
    // 终点
    const end = item.value.logisticsInfo.pop()

    driving.search(
      [start?.longitude, start?.latitude],
      [end?.longitude, end?.latitude],
      {
        waypoints: res.data.logisticsInfo.map((item: any) => [
          item.longitude,
          item.latitude
        ])
      },
      (status: string, result: object) => {
        // 未出错时，result即是对应的路线规划方案
        console.log(status, result)
      }
    )
  })
})
</script>

<template>
  <div id="myMap"></div>
</template>

<style lang="scss" scoped>
#myMap {
  height: 333px;
}
</style>
